﻿/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

/**
 * @param {String} id
 * @param {Array} list
 * @returns
 */
export function getRoomInfoById(id, list){
	let result = null;
	const find = (id, list) => {
		for(let i = 0; i < list.length; i ++){
			let item = list[i]
			if(item.id == id){
				result = item
				break
			}else {
				if(item && item.children && item.children.length > 0){
					getRoomInfoById(id, item.children)
				}
			}
		}
	}
	find(id, list)
	return result;
}

/**
 * 根据名称获取id
 * @param {目标名称} name
 * @param {源数组} originArr
 * @return {目标名称} String
 */
export function getIdByname(name, originArr, pid){
	let result = null;
	const find = (name, originArr, pid) => {
		for(let i = 0; i < originArr.length; i++){
			let item = originArr[i]
			if(pid){
				if(pid == item.pid && item.label == name){
					result = item
					break
				}else {
					if(item.children && item.children.length > 0 ){
						find(name, item.children, pid)
					}
				}
			}else {
				if(item.label == name){
					result = item
					break
				}else {
					if(item.children && item.children.length > 0 ){
						find(name, item.children)
					}
				}
			}
		}
	}
	find(name, originArr, pid)
	return result
}

/**
 *
 * 金额转换
 * */
//金额格式转换
export function parsePrice(x) {
  let f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  f = Math.round(x * 100) / 100;
  let s = f.toString();
  let rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}

/**
 * arr 源数据
 * index 取源数组的下标
 * resultList 目标id
 * return 返回值
 */
export function getTatgetId(orignArr, targetArr){
	if(orignArr.length == 0){
		return []
	}
	let item = orignArr[0]
	if(item.id){
		targetArr.push(item.id)
	}
	if(item != null && item.children != null && item.children.length > 0){
		getTatgetId(item.children, targetArr)
	}
	return targetArr
}

/**
 * 获取所有树id
 * @param {源数组} orignArr
 * @param {树id} targetArr
 * @returns 全部树id
 */
export function getTreeId(orignArr, targetArr){
	for(let i = 0; i < orignArr.length; i++){
		let item = orignArr[i]
		if(item.id){
			targetArr.push(item.id)
		}
		if(item.children && item.children.length > 0){
			getTreeId(item.children, targetArr)
		}
	}
	return targetArr
}

/**
 * 创建文件路径
 */
export function createFilePath(name, file) {
	// return name + "/" + getCurrentDay(new Date()) + "/" + file.uid + "/" + encodeURI(file.name);
	return name + "/" + getCurrentDay(new Date()) + "/" + file.uid + "/" + file.name
}

/**
 * 把对象的值转成字符串
 */
export function resetValue(obj) {
	Object.keys(obj).forEach(key => {
		if (Object.prototype.toString.call(obj[key]) === "[object Object]") {
			resetValue(obj[key])
		} else {
			obj[key] = ""
		}
	})
}

// 获取日期年月日
export function getCurrentDay(date) {
	return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate()
}

// 根据id 获取所有父id
export function getParentId(originArr, id) {
	let result = []
	let find = (arr, id) => {
		for (let i = 0; i < arr.length; i++) {
			let item = arr[i]
			let nodeId = item.baseNeighborhoodId || item.baseBuildingId || item.baseUnitId || item.baseFloorId || item.baseHouseholderId
			if (item.id === id) {
				result.push(item)
				find(originArr, nodeId)
				break
			} else {
				if (item.children) {
					find(item.children, id)
				}
			}
		}
	}
	find(originArr, id)
	return result
}

// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 表单重置
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields();
	}
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
	var search = params;
	search.params = {};
	if (null != dateRange && '' != dateRange) {
		if (typeof (propName) === "undefined") {
			search.params["beginTime"] = dateRange[0];
			search.params["endTime"] = dateRange[1];
		} else {
			search.params["begin" + propName] = dateRange[0];
			search.params["end" + propName] = dateRange[1];
		}
	}
	return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	var actions = [];
	Object.keys(datas).some((key) => {
		if (datas[key].dictValue == ('' + value)) {
			actions.push(datas[key].dictLabel);
			return true;
		}
	})
	return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
	var actions = [];
	var currentSeparator = undefined === separator ? "," : separator;
	var temp = value.split(currentSeparator);
	Object.keys(value.split(currentSeparator)).some((val) => {
		Object.keys(datas).some((key) => {
			if (datas[key].dictValue == ('' + temp[val])) {
				actions.push(datas[key].dictLabel + currentSeparator);
			}
		})
	})
	return actions.join('').substring(0, actions.join('').length - 1);
}

// 通用下载方法
export function download(fileName) {
	window.location.href = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments, flag = true, i = 1;
	str = str.replace(/%s/g, function () {
		var arg = args[i++];
		if (typeof arg === 'undefined') {
			flag = false;
			return '';
		}
		return arg;
	});
	return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str == "undefined" || str == "null") {
		return "";
	}
	return str;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}

/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params) {
	let result = ''
	Object.keys(params).forEach((key) => {
		if (!Object.is(params[key], undefined) && !Object.is(params[key], null) && !Object.is(JSON.stringify(params[key]), '{}')) {
			result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
		}
	})
	return result
}

/**
 * 比较时间
 * */
export function compareDate(params) {
  let date = new Date(params)
  let time = date.getTime()
  return time
}
